package com.etoak.service.impl;

import cn.hutool.core.date.DateUtil;
import com.etoak.common.core.exception.CustomException;
import com.etoak.common.core.vo.PageVO;
import com.etoak.entity.Dishes;
import com.etoak.mapper.DishesMapper;
import com.etoak.service.DishesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.etoak.vo.DishesVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author etoak
 * @since 2025-08-25
 */
@Service
public class DishesServiceImpl extends ServiceImpl<DishesMapper, Dishes> implements DishesService {
    //添加菜品
    @Override
    public void add(Dishes dishes) {
        if(ObjectUtils.isNotEmpty(getByName(dishes.getName()))){
            throw new CustomException("菜品名称重复");
        }
        dishes.setCreateTime(DateUtil.now());
        this.save(dishes);
    }
    private Dishes getByName(String dishesName){
        return lambdaQuery().eq(Dishes::getName,dishesName).one();
    }
    //分页查询
    @Override
    public PageVO<DishesVO> getList(int pageNum, int pageSize, Dishes dishes) {
        PageHelper.startPage(pageNum,pageSize);
        List<DishesVO> dishesVOS = baseMapper.getList(dishes);
        PageInfo<DishesVO> pageInfo = new PageInfo<>(dishesVOS);
        return new PageVO<>(pageInfo.getTotal(),dishesVOS);
    }
    //更新菜品
    @Override
    public void updateDishes(int id, Dishes dishes) {
        if(ObjectUtils.isEmpty(this.getById(id))){
            throw new CustomException("该菜品不存在");
        }
        String dishesName = dishes.getName();
        if (StringUtils.isNotBlank(dishesName)){
            Dishes savedDishes = this.getByName(dishesName);
            if (ObjectUtils.isNotEmpty(savedDishes)&& !savedDishes.getId().equals(id)){
                throw new CustomException("不能将菜品名称改为其他菜品名称");
            }
        }
        dishes.setId(id);
        dishes.setUpdateTime(DateUtil.now());
        this.updateById(dishes);
    }
    //删除菜品
    @Override
    public void deleteDishes(int id) {
        if(ObjectUtils.isEmpty(this.getById(id))){
            throw new CustomException("该菜品不存在");
        }
        this.removeById(id);
    }
}
